import { getToken, removeToken, setToken } from '@/utils/auth'
import { getUserInfo, login } from '@/api/user'

/**
 * @type {import("vuex").Module}
 */

const user = {
  namespaced: true,
  state: {
    token: getToken(), // vuex的默认token需要从本地存储获取
    userInfo: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken // 把token存储到vuex中
      // 存储本地token
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 登录的接口在actions里面进行调用
    async handleLogin(ctx, payload) {
      const res = await login(payload)
      console.log(res)
      // 存储到本地和vuex
      ctx.commit('setToken', res)
    },
    async getUserInfo(ctx) {
      const userInfo = await getUserInfo()
      ctx.commit('setUserInfo', userInfo)
    },
    async logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('setUserInfo', {})
    }
  }
}
export default user
